package com.xiaoyu.merchant.ui.fragment.store;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.adapter.AllPowerfulAdapter;
import com.xiaoyu.commonlib.ui.base.BaseFragment;
import com.xiaoyu.commonlib.ui.widget.AutofitHeightViewPager;
import com.xiaoyu.commonlib.ui.widget.RatingBar;
import com.xiaoyu.commonlib.utils.CCircleImageView;
import com.xiaoyu.commonlib.utils.PreferencesUtil;
import com.xiaoyu.commonlib.utils.ToastUtil;
import com.xiaoyu.merchant.MerchantConstants;
import com.xiaoyu.merchant.R;
import com.xiaoyu.merchant.adapter.goods.CommentBean;
import com.xiaoyu.merchant.adapter.goods.CommentBean.DataBean;
import com.xiaoyu.merchant.adapter.goods.CommentBean.DataBean.CommentParam;
import com.xiaoyu.merchant.model.StoreDetailBean;
import com.xiaoyu.merchant.network.NetworkManager;
import com.xiaoyu.merchant.ui.fragment.main.StoreFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 商家评价fragment
 */
public class StoreCommentsFragment extends BaseFragment {
    private View mView;
    @BindView(R.id.comment_complex_score)
    TextView complexScore;//综合评分
    @BindView(R.id.comment_service_score_star)
    RatingBar serviceStar;//服务态度星级
    @BindView(R.id.comment_service_score_txt)
    TextView serviceScore;//服务态度评分
    @BindView(R.id.comment_goods_score_star)
    RatingBar goodsStar;//商品评价星级
    @BindView(R.id.comment_goods_score_txt)
    TextView goodsScore;//商品评价评分
    @BindView(R.id.page_list_layout)
    RecyclerView mListLayout;
    @BindView(R.id.page_refresh_layout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.page_list_no_data_layout)
    RelativeLayout mNoDataImg;

    private AllPowerfulAdapter mAdapter;
    private List<CommentParam> mList = new ArrayList<>();
    private int page = 1;
    private int totalPage;
    private String storeId;//商家id
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView == null) {
            mView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_store_comment, container, false);
            ButterKnife.bind(this, mView);
            initView();
            getCommentInfo();
        }
        ViewGroup parent = (ViewGroup) mView.getParent();
        if (parent != null) {
            parent.removeView(mView);
        }
        return mView;
    }

    private void initView() {
        Bundle bundle = getArguments();
        int pos = bundle.getInt(AutofitHeightViewPager.POSITION);
        StoreFragment.mViewPager.setViewPosition(mView,pos);
        StoreDetailBean.DataBean data = (StoreDetailBean.DataBean) bundle.getSerializable(MerchantConstants.MERCHANT_INFO);
        storeId = data.getGoodsstroreid();
        //评分
        complexScore.setText(data.getAvg());//综合评分
        serviceStar.setStar(Float.valueOf(data.getAttitudescore()));//服务态度星级
        serviceScore.setText(Float.valueOf(data.getAttitudescore())+"");//服务态度评分
        goodsStar.setStar(Float.valueOf(data.getGoodsscore()));//商品评价星级
        goodsScore.setText(Float.valueOf(data.getGoodsscore())+"");//商品评价评分

        //评价列表
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mListLayout.setLayoutManager(layoutManager);
        setAdapter(mList);

        mRefreshLayout.setOnRefreshListener(onRefreshListener);
        mRefreshLayout.setOnLoadMoreListener(onLoadMoreListener);
        mRefreshLayout.setNoMoreData(true);
    }

    private void setAdapter(List<CommentParam> mList) {
        mAdapter = new AllPowerfulAdapter<CommentParam>(R.layout.item_goods_comment,mList){
            @Override
            protected void convert(BaseViewHolder baseViewHolder, CommentParam param) {
                super.convert(baseViewHolder, param);
                CCircleImageView portraitImg = baseViewHolder.getView(R.id.item_comment_portrait_img);
                Glide.with(getActivity()).load(param.getUserphoto()).into(portraitImg);//头像
                baseViewHolder.setText(R.id.item_comment_name,param.getNickname());//昵称
                RatingBar ratingBar = baseViewHolder.getView(R.id.item_comment_score);
                ratingBar.setStar(Float.valueOf(param.getDivide()));//星级
                baseViewHolder.setText(R.id.item_comment_content,param.getTitle());//文字评价
                LinearLayout imglayout = baseViewHolder.getView(R.id.item_comment_img_layout);//图片评价
                if ( param.getImg().size() == 0){
                    imglayout.setVisibility(View.GONE);
                }else {
                    imglayout.setVisibility(View.VISIBLE);
                }
                for (int i = 0;i < param.getImg().size();i++){
                    if (i < imglayout.getChildCount()){
                        ImageView imageView = (ImageView) imglayout.getChildAt(i);
                        Glide.with(getActivity()).load(param.getImg().get(i)).into(imageView);
                    }
                }

                baseViewHolder.setText(R.id.item_comment_time,param.getGoodspingjiatime());//评价时间
            }
        };
        mListLayout.setAdapter(mAdapter);
    }


    /**
     * 刷新
     */
    private OnRefreshListener onRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh(@NonNull RefreshLayout refreshLayout) {
            page = 1;
            mList.clear();
            mAdapter.notifyDataSetChanged();
            getCommentInfo();
            mRefreshLayout.finishRefresh();
        }
    };

    /**
     * 加载更多
     */
    private OnLoadMoreListener onLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            if (page < totalPage){
                page = page + 1;
                getCommentInfo();
                mRefreshLayout.setNoMoreData(false);
                mRefreshLayout.finishLoadMore();
            }else {
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.setNoMoreData(true);
                mRefreshLayout.finishLoadMoreWithNoMoreData();
            }
        }
    };



    /**
     * 获取评论信息
     */
    private void getCommentInfo() {
        NetworkManager.getStoreCommentList(PreferencesUtil.getString(PreferencesUtil.TOKEN, ""),page, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                parseCommentInfoSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
                ToastUtil.logError("店铺评价",errorCode,errorDiscription);
            }
        });
    }

    private void parseCommentInfoSuc(String result) {
        ToastUtil.logResult("店铺评价",result);
        if (page == 1){
            mList.clear();
        }
        CommentBean bean = new Gson().fromJson(result,CommentBean.class);
        totalPage = Integer.parseInt(bean.getData().getCount());
        mList.addAll(bean.getData().getList());
        if (totalPage == 0){
            mNoDataImg.setVisibility(View.VISIBLE);
            mRefreshLayout.setVisibility(View.GONE);
        }else if (totalPage == 1){
            mRefreshLayout.setEnableLoadMore(false);
        }else {
            mRefreshLayout.setEnableLoadMore(true);
        }
        mAdapter.notifyDataSetChanged();
    }
}
